package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zhijian.medical.dao.local.FileMapper;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.entity.po.File;
import com.zhijian.medical.entity.po.FileHistory;
import com.zhijian.medical.entity.po.PersonTeachingHistory;
import com.zhijian.medical.entity.vo.request.FileSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.FileSearchVo;
import com.zhijian.medical.entity.vo.request.FileUpdateVo;
import com.zhijian.medical.entity.vo.response.FileVo;
import com.zhijian.medical.enums.FileTypeEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 文件表业务处理层
 *
 * @author HCG
 * @date 2022-01-15 20:14:22
 * @version: 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper mapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private FileHistoryService fileHistoryService;

    @Autowired
    private PersonTeachingHistoryService personTeachingHistoryService;

    @Autowired
    private NewFileService newFileService;

    @Override
    public File selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public FileVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(File file) {
        Date now = new Date();
        file.setCreateTime(now);
        file.setUpdateTime(now);
        if (file.getType() == FileTypeEnum.STUDY_DATA.getCode().byteValue()) {
            //如果是在线学习，记录下上传人，作为带教老师
            file.setExt1(CurrentUserHolder.getUser().getId() + "");
            file.setExt2(CurrentUserHolder.getUser().getName());
        }
        return mapper.insert(file) == 1 ? file.getId() : 0L;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean update(FileUpdateVo fileUpdateVo) {
        File file = this.selectById(fileUpdateVo.getId());
        AssertUtil.notNull(file, "此文件不存在或者已被删除");
        File newFile = new File();
        BeanUtils.copyProperties(fileUpdateVo, newFile);
        this.update(newFile);
        FileHistory newFileHistory = new FileHistory();
        BeanUtils.copyProperties(fileUpdateVo, newFileHistory);
        newFileHistory.setFileId(fileUpdateVo.getId());
        return fileHistoryService.insert(newFileHistory) != 0;
    }

    @Override
    public boolean update(File file) {
        Date now = new Date();
        file.setUpdateTime(now);
        return mapper.updateByPrimaryKey(file) != 0;
    }

    @Override
    public Integer count(FileSearchVo fileSearchVo) {
        return mapper.count(fileSearchVo);
    }

    @Override
    public List<FileVo> selectList(FileSearchVo fileSearchVo) {
        return mapper.selectList(fileSearchVo);
    }

    @Override
    public Page<FileVo> selectPage(FileSearchVo fileSearchVo) {
        if ((fileSearchVo.getType() == FileTypeEnum.DEVICE_CONTRACT.getCode().byteValue() ||
                fileSearchVo.getType() == FileTypeEnum.AGENTIA_CONTRACT.getCode().byteValue())
                && roleService.isJxOrSxOrFz(fileSearchVo.getRoleIds())) {
            //如果是设备或者试剂合同文件，而且角色是外部人员，则不返回数据
            return new Page<>(true, 0, 1, 10);
        }
        //先直接查总数
        int count = count(fileSearchVo);
        //分页
        Page<FileVo> page = new Page<>(true, count, fileSearchVo.getPageNum(), fileSearchVo.getPageSize());
        fileSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<FileVo> responseVos = this.selectList(fileSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean study(Long fileId) {
        //学习，目的是给带教老师增加一条带教记录
        File file = this.selectById(fileId);
        if (ObjectUtil.isNotNull(file)) {
            return personTeachingHistoryService.insert(PersonTeachingHistory.builder()
                    //当type为学习模块的时候，ext1为带教老师用户ID，就是上传者
                    .personId(Long.valueOf(file.getExt1()))
                    .studentPersonId(CurrentUserHolder.getUser().getId())
                    .studentName(CurrentUserHolder.getUser().getName())
                    .content(file.getName())
                    .build()) != 0;
        }
        return false;
    }

    @Override
    public void preview(Long id, HttpServletResponse resp) {
        File newFile = this.selectById(id);
        if (Objects.isNull(newFile)) {
            return;
        }
        String filePath = newFile.getPath();
        if (StringUtils.isBlank(filePath)) {
            return;
        }
        newFileService.preview(filePath, resp);
    }

    @Override
    public boolean insertBatch(List<FileSaveOrUpdateVo> saveOrUpdateVoList, Byte type, Long dataId) {
        //默认PC
        return insertBatch(saveOrUpdateVoList, type, dataId, CurrentUserHolder.getUser());
    }

    @Override
    public boolean insertBatch(List<FileSaveOrUpdateVo> saveOrUpdateVoList, Byte type, Long dataId, PersonDto userDto) {
        if (CollectionUtil.isNotEmpty(saveOrUpdateVoList)) {
            Date now = new Date();
            return this.insertBatch(saveOrUpdateVoList.stream().map(g -> {
                File file = new File();
                file.setPath(g.getFilePath());
                file.setName(g.getFileName());
                file.setDataId(dataId);
                file.setType(type);
                file.setCreateTime(now);
                file.setUpdateTime(now);
                return file;
            }).collect(Collectors.toList()));
        }
        return false;
    }

    @Override
    public boolean insertBatch(List<File> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(FileSearchVo fileSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(fileSearchVo);
    }

}